﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk;
using McTools.Xrm.Connection;
using System.Configuration;
using System.IO;
using CRMTestApp.DownloadFiles;
using System.Linq;
using Microsoft.Xrm.Sdk.Messages;
using McTools.Xrm.Connection.WinForms;

namespace CRMTestApp
{
    public partial class CRMCodeTester : Form
    {
        IOrganizationService service;
        CrmConnectionStatusBar ccsb;
        ConnectionManager cManager;
        private FormHelper formHelper;

        public CRMCodeTester()
        {
            InitializeComponent();
            RunButtonEnability(false);
            this.cManager = new ConnectionManager();
            this.cManager.ConnectionSucceed +=new ConnectionManager.ConnectionSucceedEventHandler(cManager_ConnectionSucceed);
            this.cManager.ConnectionFailed += new ConnectionManager.ConnectionFailedEventHandler(cManager_ConnectionFailed);
            this.cManager.StepChanged += new ConnectionManager.StepChangedEventHandler(cManager_StepChanged);
            this.cManager.RequestPassword += new ConnectionManager.RequestPasswordEventHandler(cManager_RequestPassword);
            this.cManager.UseProxy += new ConnectionManager.UseProxyEventHandler(cManager_UseProxy);
            formHelper = new FormHelper(this, cManager);

            // Instantiate and add the connection control to the form
            ccsb = new CrmConnectionStatusBar(this.cManager, formHelper);
            this.Controls.Add(ccsb);

            this.ccsb.SetMessage("A message to display...");
        }

        void cManager_UseProxy(object sender, UseProxyEventArgs e)
        {
            formHelper.SelectProxy();
        }

        bool cManager_RequestPassword(object sender, RequestPasswordEventArgs e)
        {
            return formHelper.RequestPassword(e.ConnectionDetail);
        }

        void cManager_StepChanged(object sender, StepChangedEventArgs e)
        {
            this.ccsb.SetMessage(e.CurrentStep);
        }

        void cManager_ConnectionFailed(object sender, ConnectionFailedEventArgs e)
        {
            // Set error message
            this.ccsb.SetMessage("Error: " + e.FailureReason);

            // Clear the current organization service
            this.service = null;
        }

        void cManager_ConnectionSucceed(object sender, ConnectionSucceedEventArgs e)
        {
            ccsb.RebuildConnectionList();

            // Store connection Organization Service
            this.service = e.OrganizationService;

            // Displays connection status
            this.ccsb.SetConnectionStatus(true, e.ConnectionDetail);

            // Clear the current action message
            this.ccsb.SetMessage(string.Empty);

            // Do action if needed
            if (this.service != null)
            {
                LoadEntities();
                RunButtonEnability(true);
            }
        }

        int i;
        BackgroundWorker worker;
        private void button1_Click(object sender, EventArgs e)
        {
            i = 1;
            worker = new BackgroundWorker();
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.WorkerReportsProgress = true;
            worker.RunWorkerAsync();

        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //lblStatus.Text = string.Format("{0} out of {1} {2} completed", i, e.ProgressPercentage, e.UserState.ToString());
            lblStatus.Text = e.UserState.ToString();
            lblStatus.Refresh();
            i++;
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (service != null)
            {
                try
                {
                    string SelectedEntity = "";
                    drpEntities.Invoke(new Action(() =>
                    {
                        SelectedEntity = ((KeyValuePair<string,string>)drpEntities.SelectedItem).Value;
                    }));

                    ExportEntityData ExportTool = new ExportEntityData(SelectedEntity);
                    ExportTool.Activate(service, worker);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Service Unavailable");
            }

        }


        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show(string.Format("data for {0} downloaded successfully on file system (format : csv)", drpEntities.SelectedItem.ToString()));
        }

        private void LoadEntities()
        {
            RetrieveAllEntitiesRequest entites = new RetrieveAllEntitiesRequest()
            {
                EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Entity,
                RetrieveAsIfPublished = true
            };

            RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)service.Execute(entites);

            List<KeyValuePair<string, string>> Entities = new List<KeyValuePair<string, string>>();
            Entities.Add(new KeyValuePair<string, string>("1. Download E-mail Attachment", "downloademailattachment"));
            Entities.Add(new KeyValuePair<string, string>("2. Download Note Attachment", "downloadnoteattachment"));

            Entities.AddRange(
                response.EntityMetadata.Select(p => new KeyValuePair<string, string>(p.DisplayName.UserLocalizedLabel == null ? p.LogicalName : p.DisplayName.UserLocalizedLabel.Label, p.LogicalName)).ToList<KeyValuePair<string, string>>());

            drpEntities.DataSource = Entities.OrderBy(p => p.Key).ToList();
            drpEntities.DisplayMember = "Key";
            drpEntities.ValueMember = "Value";

            drpEntities.SelectedIndex = 2;
        }

        public void RunButtonEnability(bool flag)
        {
            btnRun.Enabled = flag;
            drpEntities.Enabled = flag;
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Thank you very much wumpus1 for about box here, http://www.codeproject.com/Articles/7390/About-The-About-Box

            AboutBoxDemo.AboutBox about = new AboutBoxDemo.AboutBox()
            {
                AppTitle = "%title%",
                AppDescription = "%product% is %copyright%, %trademark%",
                AppVersion = "Version %version%",
                AppCopyright = "Copyright © %year%, %company%",
                AppMoreInfo = "%description%",
                AppDetailsButton = true,
                Owner = this
            };
            about.ShowDialog();
        }

    }

    public class ClosureConfig
    {
        public DateTime Start { get; set; }
        public DateTime End { get; set; }
    }
}





